import {DeleteOutlined, ExclamationCircleOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {FooterToolbar, PageContainer, ProDescriptions, ProTable,} from '@ant-design/pro-components';
import {Button, Drawer, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import type {OperationLogListItem} from "@/pages/log/OperationLogList/data";
import {queryOperationLogList, removeOperationLog} from "@/pages/log/OperationLogList/service";

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: OperationLogListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeOperationLog(
      selectedRows.map((row) => row.id),
    );
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const OperationLogList: React.FC = () => {


  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<OperationLogListItem>();
  const [selectedRowsState, setSelectedRows] = useState<OperationLogListItem[]>([]);

  const showDeleteConfirm = (item: OperationLogListItem) => {
    Modal.confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined/>,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        handleRemove([item]).then(() => {
          actionRef.current?.reloadAndRest?.();
        });
      },
      onCancel() {
      },
    });
  };

  const columns: ProColumns<OperationLogListItem>[] = [
    {
      title: "id",
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: "操作者ID",
      dataIndex: 'userId',
    },
    {
      title: "操作者姓名",
      dataIndex: 'userName',
      render: (dom, entity) => {
        return <a onClick={() => {
          setCurrentRow(entity)
          setShowDetail(true)
        }
        }>{dom}</a>;
      },
    },
    {
      title: "IP地址",
      dataIndex: 'ipAddress',
      render: (dom, entity) => {
        return <a onClick={() => {
          setCurrentRow(entity)
          setShowDetail(true)
        }
        }>{dom}</a>;
      },
    },
    {
      title: "操作url",
      dataIndex: 'operationUrl',
      render: (dom, entity) => {
        return <a onClick={() => {
          setCurrentRow(entity)
          setShowDetail(true)
        }
        }>{dom}</a>;
      },
    },
    {
      title: "操作方法",
      dataIndex: 'operationMethod',
    },
    {
      title: "操作描述",
      dataIndex: 'operationDesc',
    },
    {
      title: "操作状态",
      dataIndex: 'operationStatus',
      valueEnum: {
        0: {text: '失败', status: 'Error'},
        1: {text: '成功', status: 'Success'},
      },
    },
    {
      title: "请求参数",
      dataIndex: 'requestParams',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: "操作结果",
      dataIndex: 'responseParams',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: "异常消息",
      dataIndex: 'errMessage',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: "详细的异常信息",
      dataIndex: 'errMessageDetail',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: "耗时",
      dataIndex: 'useTime',
      hideInSearch: true,
    },
    {
      title: "操作时间",
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: "操作",
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <>
          <Button
            type="primary"
            danger
            // disabled={!hasPm("/api/system/user/delete")}
            onClick={() => {
              showDeleteConfirm(record);
            }}
          >
            <DeleteOutlined/>删除
          </Button>
        </>
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<OperationLogListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={queryOperationLogList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        pagination={{pageSize: 10}}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{fontWeight: 600}}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            type={"primary"}
            danger
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <DeleteOutlined/>批量删除
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.userName && (
          <ProDescriptions<OperationLogListItem>
            column={2}
            title={currentRow?.operationDesc}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<OperationLogListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default OperationLogList;
